package com.qf.gateway.web;

import com.alibaba.fastjson.JSON;
import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.exceptions.JWTVerificationException;
import com.qf.pojo.User;
import org.springframework.cloud.gateway.filter.GatewayFilter;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.util.List;

/**
 * 用户登录认证过滤器
 */
public class AuthorizationFilter implements GlobalFilter, Ordered {

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        //排除白名单
        //检查token
        List<String> tokenList = exchange.getRequest().getHeaders().get("token");
        if (null == tokenList || tokenList.isEmpty()) {
            //请求没带token
            System.out.println("token is empty...");
            exchange.getResponse().setStatusCode(HttpStatus.UNAUTHORIZED);
            return exchange.getResponse().setComplete();
        }
        String token = tokenList.get(0);
        System.out.println("=====" + token);

        //校验token
        String userId = JWT.decode(token).getAudience().get(0);
        //根据userId获取用户密码
        User dbUser = findUserById(userId);
        //比较用户密码
        JWTVerifier verifier = JWT.require(Algorithm.HMAC256(dbUser.getPassword())).build();
        try {
            verifier.verify(token);
        } catch (JWTVerificationException e) {
            System.out.println("token验证失败");
            exchange.getResponse().setStatusCode(HttpStatus.UNAUTHORIZED);
            return exchange.getResponse().setComplete();
        }
        //将用户信息透传给到业务服务
        exchange.getRequest().mutate().header("user", JSON.toJSONString(dbUser));
        return chain.filter(exchange);
    }

    private User findUserById(String userId) {
        User user = new User();
        user.setId(1l);
        user.setPassword("123456");
        return user;
    }

    @Override
    public int getOrder() {
        //优先级设定，值越大优先级越低
        return -100;
    }
}
